package com.okay.udp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;

import com.okay.testclass.R;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


/**
 * 这个是udpSocket的小demo
 */
public class UdpActivity extends FragmentActivity {


    private TextView ms_chatmsg;
    private EditText ms_editext;
    private Button ms_send;
    private StringBuilder builder;

    DatagramSocket socket;

    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch ( msg.what) {
                case 0x1001:
                    ms_chatmsg.setText(builder.toString());
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_udp);

        ms_chatmsg =   findViewById(R.id.ms_chatmsg);
        ms_editext =   findViewById(R.id.ms_edit);
        ms_send =   findViewById(R.id.ms_send);

        builder  = new StringBuilder();

        initSocket();

        ms_send.setOnClickListener(v -> {


            new Thread(new Runnable() {
                public void run() {
                    try {
                    sendMsg( ms_editext.getText().toString());
                    } catch (Exception e )
                    {
                        e.printStackTrace();
                    }
                }
            }).start();
        });


        new Thread(new Runnable() {
            public void run() {
                while(true){
                    try {
                        receiveMsg();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();




    }

    private void initSocket(){
        // 3.创建DatagramSocket对象
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    private void closeSocket(){
        // 4.关闭资源
        socket.close();
    }

    private void sendMsg(String ss) throws IOException {
        /*
         * 向服务器端发送数据
         */
        // 1.定义服务器的地址、端口号、数据
        // 注意 ip 要替换成你的
        InetAddress address = InetAddress.getByName("10.60.109.67");
        int port = 12345;
        byte[] data = ss.getBytes();

        builder.append("<<< 你好，我是客户端\n");

        builder.append("看看服务器有没有啥回复\n");

        handler.sendEmptyMessage(0x1001);

        // 2.创建数据报，包含发送的数据信息
        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
        // 4.向服务器端发送数据报
        socket.send(packet);
    }

    private void receiveMsg() throws IOException {
        /*
         * 接收服务器端响应的数据
         */
        // 1.创建数据报，用于接收服务器端响应的数据
        byte[] data2 = new byte[1024];
        DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
        // 2.接收服务器响应的数据
        socket.receive(packet2);
        // 3.读取数据
        String reply = new String(data2, 0, packet2.getLength());

        builder.append(">>> 我是客户端，服务器说：" + reply+"\n");
        handler.sendEmptyMessage(0x1001);

    }

}
